﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Portal.BO.Editoral.Statistic;

using System.Collections;
using Dundas.Charting.WebControl;
using Portal.Core.DAL;
using Xmobile.Users;


namespace Portal.GUI.EditoralOffice.MainOffce.Statistics
{

    public partial class statistic : System.Web.UI.UserControl
    {
        public double MaxChartValue;
        public const int MaxRes = 200;
        
        
        protected void Page_Load(object sender, EventArgs e)
        {
            lblError.Visible = false;
            

            if (!IsPostBack)
            {
                drpChartType.Visible = true;
                txtEnd_Date.SelectedDate = DateTime.Today;
                txtStart_Date.SelectedDate = DateTime.Today.AddDays(-7);

                /// Lay QueryString cua Content
                Int64 _contentId = -1;
                try
                {
                    _contentId = Convert.ToInt64(Request.QueryString["contentid"].ToLower());
                }
                catch
                {
                    _contentId = -1; //error
                }

                // Lay QueryString theo CategoryId
                string _catId = "";
                try
                {
                    _catId = Request.QueryString["catid"].ToString().Trim();
                    if (_catId.Trim() != "") 
                    {
                        string[] arCatId = _catId.Split(',');
                        _catId = "";
                        foreach (string s in arCatId) 
                        {
                            _catId = _catId + "'" + s + "',";
                        }
                        _catId = _catId.Substring(0,_catId.Length-1);
                    }
                }
                catch
                {
                    _catId = ""; //error
                }

                // Lay QueryString theo UserId
                string _userId = "";
                try
                {
                    _userId = Request.QueryString["userid"].ToString().Trim();
                    if (_userId.Trim() != "")
                    {
                        string[] arUserId = _userId.Split(',');
                        _userId = "";
                        foreach (string s in arUserId)
                        {
                            _userId = _userId + "'" + s + "',";
                        }
                        _userId = _userId.Substring(0, _userId.Length - 1);
                    }
                }
                catch
                {
                    _userId = ""; //error
                }


                // Bind du lieu vao cbx KieuThongke
                drpReportType.DataSource = (new VisualReport()).GenerateCountKeyDesc(_contentId, _catId, _userId); 
                drpReportType.DataTextField = "CountKeyText";
                drpReportType.DataValueField = "CountKeyValue";
                drpReportType.DataBind();
                
                
            }
        }

        
        private void BindGrid(ArrayList data, bool ShowZValue, int iCell)
        {
            //ValueByDateGrid.Visible = true;
            pnlDataGrid.CssClass = "DisplayInline";
            Chart1.CssClass = "DisplayNone";

            ValueByDateGrid.DataSource = data;
            ValueByDateGrid.Columns[iCell].Visible = ShowZValue;
            ValueByDateGrid.DataBind();
        }

        public void Item_Bound(Object sender, DataGridItemEventArgs e)
        {
            if ((e.Item.ItemType == ListItemType.Item) ||
                (e.Item.ItemType == ListItemType.AlternatingItem))
            {
                VisualReport vr = (VisualReport)e.Item.DataItem;
                /*string s = vr.XValue;
                if ((e.Item.Cells[0].Text.Length == s.Length) & s.Length >= 10)
                {
                    DateTime date = Convert.ToDateTime(s);
                    s = date.ToString("d/M/yy");
                    vr.XValue = s;
                    e.Item.Cells[0].Text = vr.XValue;
                }*/

                if (e.Item.Cells[1].Text == vr.ZValue && CheckIsCategoryReport())
                {
                    string strCatId = vr.ZValue;
                    if (strCatId != "" && strCatId != "-1")
                    {
                        using (Portal.Core.DAL.MainDB mainDb = new Portal.Core.DAL.MainDB())
                        {
                            //Portal.Core.DAL.CategoryRow[] catRow = mainDb.CategoryCollection.GetAsArray(" Cat_ID = " + strCatId, "");
                            //if (catRow.Length > 0)
                            //{
                            //    if (catRow[0].Cat_Name.Trim() != String.Empty)
                            //        e.Item.Cells[1].Text = catRow[0].Cat_Name;
                            //}

                            DataTable catRow = mainDb.FrontEndStoreProcedure.Category_GetListByWhere(" Where  Cat_ID = " + strCatId, "");
                            if (catRow.Rows.Count > 0)
                            {
                                e.Item.Cells[1].Text = catRow.Rows[0]["Cat_Name"].ToString();
                            }
                        }
                        
                    }
                }

                if (e.Item.Cells[1].Text == vr.ZValue && CheckIsReportByUser())
                {
                    string strUserId = vr.ZValue;
                    if (strUserId != "" && strUserId != "-1")
                    {
                        using (Xmobile.Users.MainDB mainDb = new Xmobile.Users.MainDB())
                        {
                            //UserRow[] userRow = mainDb.UserCollection.GetAsArray(" User_ID =  '" + strUserId + "'", "");
                            //if (userRow.Length > 0)
                            //{
                            //    if (userRow[0].User_Name.Trim() != String.Empty)
                            //    {
                            //        e.Item.Cells[2].Text = userRow[0].User_Name;
                            //        e.Item.Cells[2].Visible = true;
                            //    }
                            //}
                            DataTable userRow = mainDb.StoreProcedure.vc_Execute_Sql(" SELECT * FROM [User] Where User_ID =  '" + strUserId + "'");
                            if (userRow.Rows.Count > 0)
                            {
                                e.Item.Cells[2].Text = userRow.Rows[0]["User_Name"].ToString();
                                e.Item.Cells[2].Visible = true;
                            }
                        }

                    }
                }
            }
        }


        private void drpChartType_SelectedIndexChanged(object sender, System.EventArgs e)
        {
           
        }

        private void GoError(string ErrMsg)
        {
            if (ErrMsg == "")
            {
                lblError.Visible = false; //Clear error
            }
            else
            {
                lblError.Visible = true;
                lblError.Text = ErrMsg;
                //ChartImage.Visible = false;
                //ValueByDateGrid.Visible = false;
            }
        }

        
       
        private void btnReport_Click(object sender, System.EventArgs e)
        {
            //ValueByDateGrid.Visible = true;
            //ValueByDateGrid.cs

            string strCountKey = drpReportType.SelectedItem.Value.ToString();
           
            string strStartDate, strEndDate;


            // Lấy các Category ID của chuyên mục cần thống kê
            string strID = "'-1'";
            if(CheckIsCategoryReport())
            {
                try
                {
                    strID = Request.QueryString["catid"].ToString().Trim();
                    if (strID.Trim() != "")
                   {
                       string[] arCatId = strID.Split(',');
                       strID = "";
                       foreach (string s in arCatId)
                       {
                           strID += "'" + s + "',";
                       }
                       strID = strID.Substring(0, strID.Length - 1);
                   }
                }
                catch
                {
                    strID = "'-1'";
                }
            }

            // Lấy contentID cần thống kê
            if (drpReportType.SelectedValue == ((int)CountKey.Content_View).ToString()) 
            {
                
                try
                {
                    strID = "'" + Request.QueryString["contentid"] + "'";
                }
                catch
                {
                    strID = "'-1'";
                }
            }

            // Lấy User ID cần thống kê
            if (CheckIsReportByUser()) 
            {
                try
                {
                    strID = Request.QueryString["userid"].ToString().Trim();
                    if (strID.Trim() != "")
                    {
                        string[] arCatId = strID.Split(',');
                        strID = "";
                        foreach (string s in arCatId)
                        {
                            strID += "'" + s + "',";
                        }
                        strID = strID.Substring(0, strID.Length - 1);
                    }
                }
                catch
                {
                    strID = "'-1'";
                }

            }
            

            string strMinValue = txtMinValue.Text.ToString();
            string strMaxValue = txtMaxValue.Text.ToString();

            strStartDate = Convert.ToDateTime(txtStart_Date.SelectedDate.ToString()).ToString("yyyyMMdd");
            strEndDate = Convert.ToDateTime(txtEnd_Date.SelectedDate.ToString()).ToString("yyyyMMdd");
            
           
            if (drpChartType.SelectedItem.Value != "Table")
            {
                if (drpChartType.SelectedValue == "Line")
                {
                    DrawChart("line",strID, strCountKey, strStartDate, strEndDate, strMinValue, strMaxValue);
                }
                else
                    if (drpChartType.SelectedValue == "Bar")
                    {
                        DrawChart("bar", strID, strCountKey, strStartDate, strEndDate, strMinValue, strMaxValue);
                    }

                
            }
            else
            {
                VisualReport visualReport = null;
                visualReport = new VisualReport();

                switch (drpGroupBy.SelectedValue.ToLower())
                {
                    case "day":
                        visualReport = new VisualReport().GetReport(strCountKey, strID, strStartDate, strEndDate, strMinValue, strMaxValue);
                        break;
                    case "week":
                        visualReport = new VisualReport().GetReportByWeek(strCountKey, strID, strStartDate, strEndDate, strMinValue, strMaxValue);
                        break;
                    case "month":
                        visualReport = new VisualReport().GetReportByMonth(strCountKey, strID, strStartDate, strEndDate, strMinValue, strMaxValue);
                        break;
                    case "quater":
                        visualReport = new VisualReport().GetReportByQuater(strCountKey, strID, strStartDate, strEndDate, strMinValue, strMaxValue);
                        break;
                    case "year":
                        visualReport = new VisualReport().GetReportByYear(strCountKey, strID, strStartDate, strEndDate, strMinValue, strMaxValue);
                        break;
                }
                
                if (visualReport == null)
                {
                    GoError("Lỗi : Không tìm thấy dữ liệu phù hợp");
                    Chart1.CssClass = "DisplayNone";
                    pnlDataGrid.CssClass = "DisplayNone";
                    return;
                }

                ChartThongKe(visualReport);
            }
        }

        private void ChartThongKe(VisualReport visualReport)
        {
            int rowCount = visualReport.Count;
            MaxChartValue = 0.0;
            
            if (rowCount != 0)
            {
                foreach (VisualReport dr in visualReport)
                {
                    if (MaxChartValue < Convert.ToDouble(dr.Value))
                        MaxChartValue = Convert.ToDouble(dr.Value);
                }
                MaxChartValue = MaxRes / MaxChartValue;
                //int i = 0;
                int j = 0;
                string LuuValue = "";

                foreach (VisualReport dr in visualReport)
                {

                    dr.ImageUrl = "/Images/bar0.gif";

                    dr.MaxValue = Convert.ToDecimal(Convert.ToDouble(dr.Value) * MaxChartValue);
                    LuuValue = dr.XValue.ToString();
                    j++;
                }


                if (CheckIsCategoryReport())
                    BindGrid(visualReport, true, 1);
                else
                if (CheckIsReportByUser()) {
                   BindGrid(visualReport, true, 2);
                }
                else BindGrid(visualReport, false, 1);
                
            }
        }

        private void DrawChart(string chartType,string strID, string strCountKey, string strStartDate, string strEndDate, string strMinValue, string strMaxValue)
        {

            // Bieu do Line
            string[] aId = strID.Split(',');
            for (int i = 0; i < aId.Length; i++)
            {
               ArrayList visualReport = new VisualReport().GetReport(strCountKey, aId[i], strStartDate, strEndDate, strMinValue, strMaxValue);
               SqlDataReader dr = null;

               if (drpGroupBy.SelectedValue == "day")
                   dr = new VisualReport().GetReportAsDataReader(strCountKey, aId[i], strStartDate, strEndDate, strMinValue, strMaxValue);
               else
               if (drpGroupBy.SelectedValue == "week")
                   dr = new VisualReport().GetReporByWeekAsDataReader(strCountKey, aId[i], strStartDate, strEndDate, strMinValue, strMaxValue);
               else
               if (drpGroupBy.SelectedValue == "month")
                   dr = new VisualReport().GetReporByMonthAsDataReader(strCountKey, aId[i], strStartDate, strEndDate, strMinValue, strMaxValue);
               else
               if (drpGroupBy.SelectedValue == "quater")
                   dr = new VisualReport().GetReporByQuaterAsDataReader(strCountKey, aId[i], strStartDate, strEndDate, strMinValue, strMaxValue);
               else
               if (drpGroupBy.SelectedValue == "year")
                   dr = new VisualReport().GetReporByYearAsDataReader(strCountKey, aId[i], strStartDate, strEndDate, strMinValue, strMaxValue);

               if (dr.HasRows == true)
                {
                    


                    string seriesName = " ";
                    if (CheckIsCategoryReport()) 
                    {
                        using (Portal.Core.DAL.MainDB mainDb = new Portal.Core.DAL.MainDB())
                        {
                            //Portal.Core.DAL.CategoryRow[] catRow = mainDb.CategoryCollection.GetAsArray(" Cat_ID = " + aId[i], "");
                            //if (catRow.Length > 0)
                            //{
                            //    if (catRow[0].Cat_Name.Trim() != String.Empty)
                            //    {

                            //        seriesName = catRow[0].Cat_Name;
                            //        Chart1.Series.Add(seriesName);
                            //    }

                            //}

                            DataTable catRow = mainDb.FrontEndStoreProcedure.Category_GetListByWhere(" Where Cat_ID = " + aId[i], "");
                            if (catRow.Rows.Count > 0)
                            {
                                seriesName = catRow.Rows[0]["Cat_Name"].ToString();
                                Chart1.Series.Add(seriesName);
                            }
                            
                        }
                    }
                    else
                        if (CheckIsReportByUser())
                        {
                            using (Xmobile.Users.MainDB mainDb = new Xmobile.Users.MainDB())
                            {
                                //UserRow[] userRow = mainDb.UserCollection.GetAsArray(" User_Id = " + aId[i], "");
                                //if (userRow.Length > 0)
                                //{
                                //    if (userRow[0].User_Name.Trim() != String.Empty)
                                //    {

                                //        seriesName = userRow[0].User_Name;
                                //        Chart1.Series.Add(seriesName);
                                //    }

                                //}

                                 DataTable userRow = mainDb.StoreProcedure.vc_Execute_Sql(" Select * From [User] Where User_Id = " + aId[i]);
                                 if (userRow.Rows.Count > 0)
                                 {
                                     seriesName = userRow.Rows[0]["User_Name"].ToString();
                                     Chart1.Series.Add(seriesName);
                                 }
                                
                            }
                        }
                        else {
                            seriesName = drpReportType.Items[drpReportType.SelectedIndex].ToString();
                            Chart1.Series.Add(seriesName);
                        }

                    


                    if (chartType == "line"){

                        Chart1.Series[seriesName].Type = SeriesChartType.Line;
                        //Chart1.Series["Series" + i].Points.DataBindXY(visualReport["xValues"], visualReport["yValues"]);
                        Chart1.Series[seriesName].Points.DataBind(dr, "xValues", "yValues", "Label=yValues");
                        Chart1.Series[seriesName].ShowLabelAsValue = true;
                        //Chart1.Series["Series1"].
                        Chart1.Series[seriesName]["LabelStyle"] = "Top";
                        Chart1.Series[seriesName].Type = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), "Spline", true); ;
                        Chart1.Series[seriesName].BorderWidth = 2;
                        Chart1.Series[seriesName].MarkerStyle = MarkerStyle.Circle;

                    }
                    else if(chartType == "bar"){

                        Chart1.Series[seriesName].Type = SeriesChartType.Column;
                        Chart1.Series[seriesName].Points.DataBind(dr, "xValues", "yValues", "Label=yValues");
                        Chart1.Series[seriesName].ShowLabelAsValue = true;
                        Chart1.Series[seriesName]["PointWidth"] = "0.4";
                        
                        // Draw as 3D Cylinder
                        Chart1.Series[seriesName]["DrawingStyle"] = "Cylinder";
                   }

                }

            }

            Chart1.ChartAreas["Default"].AxisX.Margin = true;
            Chart1.CssClass = "DisplayInline";
            pnlDataGrid.CssClass = "DisplayNone";
        }

        

        private bool CheckIsCategoryReport() {

            if (drpReportType.SelectedValue == ((int)CountKey.Category_View).ToString()
                || drpReportType.SelectedValue == ((int)CountKey.Category_Approved_Content).ToString()
                || drpReportType.SelectedValue == ((int)CountKey.Category_Wait_Approve_Content).ToString()
                || drpReportType.SelectedValue == ((int)CountKey.Category_Wait_Edit_Content).ToString()
                )
            {
                return true;
            }
            else
                return false;
        }

        private bool CheckIsReportByUser()
        {

            if (drpReportType.SelectedValue == ((int)CountKey.User_Approved_Content).ToString()
                || drpReportType.SelectedValue == ((int)CountKey.User_Wait_Approve_Content).ToString()
                || drpReportType.SelectedValue == ((int)CountKey.User_Wait_Edit_Content).ToString()
                )
            {
                return true;
            }
            else
                return false;
        }

        private void drpReportType_SelectIndexChange(object sender, System.EventArgs e)
        {
            
            
            
        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.drpReportType.SelectedIndexChanged += new System.EventHandler(this.drpReportType_SelectIndexChange);
            this.btnReport.Click += new System.EventHandler(this.btnReport_Click);
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion	
    }
}